package com.example.javapracticaltraining.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.dto.PasswordChangeDTO;
import com.example.javapracticaltraining.entity.pojo.Users;
import com.example.javapracticaltraining.service.UsersService;
import com.example.javapracticaltraining.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
* @author night
* @description 针对表【users】的数据库操作Service实现
* @createDate 2025-07-02 15:42:45
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public R<String> changePassword(PasswordChangeDTO passwordChangeDTO) {
        // 参数校验
        if (passwordChangeDTO == null || passwordChangeDTO.getUserId() == null) {
            return R.error("用户ID不能为空");
        }

        if (!StringUtils.hasText(passwordChangeDTO.getOldPassword())) {
            return R.error("旧密码不能为空");
        }

        if (!StringUtils.hasText(passwordChangeDTO.getNewPassword())) {
            return R.error("新密码不能为空");
        }

        // 密码长度校验
        if (passwordChangeDTO.getNewPassword().length() < 6) {
            return R.error("新密码长度不能少于6个字符");
        }

        // 查询用户
        Users user = usersMapper.selectById(passwordChangeDTO.getUserId());
        if (user == null) {
            return R.error("用户不存在");
        }

        // 验证旧密码
        // 注意：实际项目中应该对密码进行加密处理，这里为了简化直接比较明文密码
        if (!user.getPassword().equals(passwordChangeDTO.getOldPassword())) {
            return R.error("旧密码不正确");
        }

        // 更新密码
        user.setPassword(passwordChangeDTO.getNewPassword());
        int result = usersMapper.updateById(user);

        if (result > 0) {
            return R.success("密码修改成功");
        } else {
            return R.error("密码修改失败，请稍后重试");
        }
    }
}
